import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response';
import { connectToDatabase } from '@/service/mongo';
import { MongoTeamMember } from '@fastgpt/service/support/user/team/teamMemberSchema';
import {
  TeamMemberRoleEnum,
  TeamMemberStatusEnum,
  notLeaveStatus
} from '@fastgpt/global/support/user/team/constant';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    await connectToDatabase();
    const { teamId, userId, name = 'Owner' } = req.body;
    const member = await MongoTeamMember.findOne({ userId });
    if (member) {
      //   throw new Error('成员已存在');
      jsonRes(res, {
        data: '成员已存在'
      });
      return;
    }
    const data = await MongoTeamMember.create({
      teamId: teamId,
      userId,
      name: name,
      role: TeamMemberRoleEnum.admin,
      status: TeamMemberStatusEnum.active,
      createTime: new Date(),
      defaultTeam: true
    });

    jsonRes(res, {
      data
    });
  } catch (err) {
    jsonRes(res, {
      code: 500,
      error: err
    });
  }
}
